package com.example.transactionhintassistant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.transactionhintassistant.pojo.dto.task.AddTaskDto;
import com.example.transactionhintassistant.pojo.dto.task.ChangeStatusDto;
import com.example.transactionhintassistant.pojo.dto.task.EditReminderLevel;
import com.example.transactionhintassistant.pojo.dto.task.EditTaskDto;
import com.example.transactionhintassistant.pojo.entity.Memo;
import com.example.transactionhintassistant.pojo.entity.Task;
import com.example.transactionhintassistant.pojo.vo.TaskVo;
import com.example.transactionhintassistant.service.TasksService;
import com.example.transactionhintassistant.mapper.TasksMapper;
import com.example.transactionhintassistant.utils.JwtHelper;
import com.example.transactionhintassistant.utils.result.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
* @author 86147
* @description 针对表【tasks(事务表)】的数据库操作Service实现
* @createDate 2024-03-07 11:53:00
*/
@Service
public class TasksServiceImpl extends ServiceImpl<TasksMapper, Task>
    implements TasksService{

    @Autowired
    private TasksMapper tasksMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public Result<Object> getTodayTaskNow() {
        // 获取请求头中的令牌
        String token = request.getHeader("Authorization");
        int userId = jwtHelper.getUserId(token);

        // 获取当天开始和结束的精确到秒的时间
        LocalDateTime dayNow = LocalDateTime.now();
        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);

        System.out.println("2002002"+dayNow+" "+endOfDay);
        LambdaQueryWrapper<Task> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Task::getUserId, userId)
                .between(Task::getTime, dayNow, endOfDay)  // 添加时间范围条件
                .orderByAsc(Task::getTime); // 按照时间升序排序
        List<Task> taskList = tasksMapper.selectList(lambdaQueryWrapper);
        List<TaskVo> taskVoList = new ArrayList<>();

        for (Task task : taskList) {
            TaskVo taskVo = new TaskVo();
            BeanUtils.copyProperties(task, taskVo); // 将Task对象的属性复制到TaskVo对象中
            taskVoList.add(taskVo); // 添加到TaskVo列表中

        }

        return Result.ok(taskVoList, "获取今日所有事务信息成功");
    }

    @Override
    public Result<Object> getTodayTask() {
        // 获取请求头中的令牌
        String token = request.getHeader("Authorization");
        int userId = jwtHelper.getUserId(token);

        // 获取当天开始和结束的精确到秒的时间
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);

        System.out.println("110011"+startOfDay+" "+endOfDay);
        LambdaQueryWrapper<Task> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Task::getUserId, userId)
                .between(Task::getTime, startOfDay, endOfDay)  // 添加时间范围条件
                .orderByAsc(Task::getTime); // 按照时间升序排序
        List<Task> taskList = tasksMapper.selectList(lambdaQueryWrapper);
        List<TaskVo> taskVoList = new ArrayList<>();

        for (Task task : taskList) {
            TaskVo taskVo = new TaskVo();
            BeanUtils.copyProperties(task, taskVo); // 将Task对象的属性复制到TaskVo对象中
            taskVoList.add(taskVo); // 添加到TaskVo列表中

        }

        return Result.ok(taskVoList, "获取今日所有事务信息成功");
    }

    @Override
    public Result<Object> getAllTask(Integer completionStatus) {
        // 获取请求头中的令牌
        String token = request.getHeader("Authorization");
        int userId = jwtHelper.getUserId(token);

        LambdaQueryWrapper<Task> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Task::getUserId,userId);


        if (completionStatus != null) {
            lambdaQueryWrapper.eq(Task::getCompletionStatus, completionStatus); // 如果指定了状态，添加状态条件
        }

        List<Task> taskList = tasksMapper.selectList(lambdaQueryWrapper);
        List<TaskVo> taskVoList = new ArrayList<>();
        for (Task task : taskList) {
            TaskVo taskVo = new TaskVo();
            BeanUtils.copyProperties(task, taskVo); // 将Task对象的属性复制到TaskVo对象中
            taskVoList.add(taskVo); // 添加到TaskVo列表中

        }

        return Result.ok(taskVoList, "获取事务信息成功");
    }


    @Override
    public Result<Object> addTodayTask(AddTaskDto addTaskDto) {

        Task task=new Task();
        Date today = addTaskDto.getTime();
        System.out.println("事务日期："+addTaskDto.getTime());
        // 创建一个用于格式化日期的 SimpleDateFormat 对象
        SimpleDateFormat formatter = new SimpleDateFormat("EEEE", Locale.getDefault());
        // 使用格式化器获取今天是星期几的字符串表示
        String dayOfWeekString = formatter.format(today);


//        Task task = new Task();
//
//        // 将 Date 转换为 LocalDateTime
//        Date date = addTaskDto.getTime();
//        Instant instant = date.toInstant();
//        ZoneId zoneId = ZoneId.systemDefault();
//        LocalDateTime today = LocalDateTime.ofInstant(instant, zoneId);

        // 获取当前日期是星期几
//        String dayOfWeekString = today.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.getDefault());

        // 获取请求头中的令牌
        String token = request.getHeader("Authorization");
        int userId = jwtHelper.getUserId(token);
        BeanUtils.copyProperties(addTaskDto,task);
        task.setUserId(userId);
        task.setCreatedTime(new Date());
        task.setDayOfWeek(dayOfWeekString);
        task.setTime(addTaskDto.getTime());
        task.setCompletionStatus(2); //默认下状态为未完成
        this.save(task);
        return Result.ok(null,"添加事务成功");
    }

    @Override
    public Result<Object> editTodayTask(EditTaskDto editTaskDto) {
        Date time = editTaskDto.getTime();
        // 创建一个用于格式化日期的 SimpleDateFormat 对象
        SimpleDateFormat formatter = new SimpleDateFormat("EEEE", Locale.getDefault());
        // 使用格式化器获取今天是星期几的字符串表示
        String dayOfWeekString = formatter.format(time);

        LambdaUpdateWrapper<Task> lambdaUpdateWrapper = new LambdaUpdateWrapper();
        lambdaUpdateWrapper.eq(Task::getId,editTaskDto.getId())
                .set(Task::getDayOfWeek,dayOfWeekString)
                .set(Task::getTime,editTaskDto.getTime())
                .set(Task::getReminderLevel,editTaskDto.getReminderLevel());
        this.update(lambdaUpdateWrapper);
        return Result.ok(null,"修改今日事务信息成功");
    }

    @Override
    public Result<Object> editReminderLevel(EditReminderLevel editReminderLevel) {
        LambdaUpdateWrapper<Task> lambdaUpdateWrapper = new LambdaUpdateWrapper();
        lambdaUpdateWrapper.eq(Task::getId,editReminderLevel.getId())
                .set(Task::getReminderLevel,editReminderLevel.getReminderLevel());
        this.update(lambdaUpdateWrapper);
        return Result.ok(null,"修改提醒级别成功");
    }

    @Override
    public Result<Object> deleteTask(Integer id) {
        tasksMapper.deleteById(id);
        return Result.ok(null,"删除事务成功");
    }

    @Override
    public Result<Object> getWeekAllInfo(Integer status) {
        // 获取请求头中的令牌
        String token = request.getHeader("Authorization");
        int userId = jwtHelper.getUserId(token);

        // 获取本周开始和结束的时间
        LocalDateTime startOfWeek = LocalDateTime.now().with(DayOfWeek.MONDAY).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endOfWeek = LocalDateTime.now().with(DayOfWeek.SUNDAY).withHour(23).withMinute(59).withSecond(59);

        // 构建查询条件
        LambdaQueryWrapper<Task> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Task::getUserId, userId)
                .between(Task::getTime, startOfWeek, endOfWeek); // 添加时间范围条件

        if (status != null) {
            lambdaQueryWrapper.eq(Task::getCompletionStatus, status); // 如果指定了状态，添加状态条件
        }

        lambdaQueryWrapper.orderByAsc(Task::getTime); // 按照时间升序排序

        // 执行查询
        List<Task> taskList = tasksMapper.selectList(lambdaQueryWrapper);

        // 构建结果列表
        List<TaskVo> taskVoList = new ArrayList<>();
        for (Task task : taskList) {
            TaskVo taskVo = new TaskVo();
            BeanUtils.copyProperties(task, taskVo); // 将Task对象的属性复制到TaskVo对象中
            taskVoList.add(taskVo); // 添加到TaskVo列表中
        }

        // 返回结果对象
        return Result.ok(taskVoList, "获取本周所有事务信息成功");
    }

    @Override
    public Result<Object> getTodayProgress() {
        // 获取请求头中的令牌
        String token = request.getHeader("Authorization");
        int userId = jwtHelper.getUserId(token);

        // 获取今天的开始时间和结束时间
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);

        // 构建查询条件
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId)
        .between("time", todayStart, todayEnd);

        List<Task> todayTasks = tasksMapper.selectList(queryWrapper);
        System.out.println("===========" + todayTasks.toString());
        if (todayTasks.size() == 0)
        {
            return Result.ok(100,"今天还没有需要处理的事务");
        }
        else {
            float unFinishNum = 0;
            for (Task item:todayTasks) {
                if (item.getCompletionStatus() == 0)
                    unFinishNum = unFinishNum + 1;
            }
            float progressNum  = (todayTasks.size() - unFinishNum) * 100 / todayTasks.size();
            if (unFinishNum == 0) {
                return Result.ok(100,"今日所有事务都已完成啦");

            }
            String formattedNum = String.format("%.1f", progressNum);
            return Result.ok(formattedNum,"今日还有"+(int)unFinishNum+"件事务未完成，加油！");
        }
    }

    @Override
    public Result<Object> changeStatus(ChangeStatusDto changeStatusDto) {

        LambdaUpdateWrapper<Task> lambdaUpdateWrapper = new LambdaUpdateWrapper();
        lambdaUpdateWrapper.eq(Task::getId,changeStatusDto.getTaskId())
                .set(Task::getCompletionStatus,changeStatusDto.getCompletionStatus());
        this.update(lambdaUpdateWrapper);
        return Result.ok(null,"修改状态成功");
    }

}




